package net.xinqushi.socket.nio;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author xjie 2019/7/17 14:57
 * @description 非阻塞Server
 *  与非阻塞比较
 *   一致的特性 : 读取数据时，如果client未标识已经写完 (client.close) ,会阻塞
 */
public class NonBlockServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(5555));
        serverSocketChannel.configureBlocking(false);
        //ServerSocketChannel可以设置成非阻塞模式。在非阻塞模式下，accept() 方法会立刻返回，如果还没有新进来的连接,返回的将是null。
        // 因此，需要检查返回的SocketChannel是否是null
        ByteBuffer buf = ByteBuffer.allocate(48);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while(true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            for(;null != socketChannel;){
                //非阻塞模式下,read()方法在尚未读取到任何数据时可能就返回了。所以需要关注它的int返回值，它会告诉你读取了多少字节。
                int readBytes = 0;
                while ( -1 != ( readBytes = socketChannel.read(buf)) ){
                    bos.write(buf.array() , 0 , readBytes);
                }
                System.out.println(new String(bos.toByteArray()));
                socketChannel.close();//标识end
                break;
            }
        }
    }
}
